package com.specialtreasure.freightdepot.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.core.activity.BaseNewActivity;
import com.app.core.config.Constants;
import com.app.core.config.HttpApi;
import com.app.core.util.KumaToast;
import com.app.core.util.UserUtils;
import com.app.core.view.MarqueeTextView;
import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.specialtreasure.freightdepot.R;
import com.specialtreasure.freightdepot.adapter.MyOrderAdapter;
import com.specialtreasure.freightdepot.model.Address;
import com.specialtreasure.freightdepot.model.AmountBean;
import com.specialtreasure.freightdepot.model.BaseModel;
import com.specialtreasure.freightdepot.model.BaseTbItemOrder;
import com.specialtreasure.freightdepot.model.TbItemOrder;
import com.specialtreasure.freightdepot.model.TbItemOrderData;
import com.specialtreasure.freightdepot.popupwindow.KMSelectCityPW;
import com.specialtreasure.freightdepot.popupwindow.SelectCity;
import com.yanzhenjie.httpmodule.http.CallServer;
import com.yanzhenjie.httpmodule.http.Result;
import com.yanzhenjie.httpmodule.http.StringRequest;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/8/21 0021.
 * 我的订单
 */

public class MyOrderActivity extends BaseNewActivity implements View.OnClickListener {
    public static final String TAG = "MyOrderActivity";
    Integer count = 10;//每页条数
    Integer page = 1;//页数
    String token;
    List<TbItemOrder> tbItemOrders = new ArrayList<TbItemOrder>();
    Boolean hasMode;
    MyOrderAdapter myOrderAdapter;

    private Address mAddressFrom = new Address();
    private Address mAddressTo = new Address();


    private ImageView iv_back;
    private TextView tv_title;
    private MarqueeTextView tv_navigation;
    private ListView lv_moto_cade;
    private PtrClassicFrameLayout ptr_layout;
    private RelativeLayout rl_from;
    private RelativeLayout rl_to;
    private RelativeLayout rl_phone;
    private TextView tv_from;
    private TextView tv_to;
    private TextView tv_phone;
    private LinearLayout ll_all;
    private TextView tv_money_tran;
    private TextView tv_money_info;
    private TextView tv_sure;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_my_order);
        EventBus.getDefault().register(this);
        initView();
        setData();
        getAD();

    }

    private void setData() {
        show(iv_back);
        tv_title.setText("我的订单");


        //初始化自动刷新
        ptr_layout.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptr_layout.autoRefresh(true);
            }
        }, 150);

        //下拉刷新
        ptr_layout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                tv_money_tran.setText("运费总计：0元");
                tv_money_info.setText("信息费总计：0元");
                ptr_layout.setLoadMoreEnable(true);
                page = 1;
                tbItemOrders.clear();
                getData();

            }
        });

        //自动加载更多
        ptr_layout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                if (!hasMode) {
                    page++;
                    getData();
                } else {
                    Toast.makeText(mContext, "没有更多数据了", Toast.LENGTH_SHORT).show();
                    ptr_layout.setLoadMoreEnable(false);
                }
            }
        });

    }


    private void initView() {
        iv_back = (ImageView) findViewById(R.id.iv_back);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_money_tran = (TextView) findViewById(R.id.tv_money_tran);
        tv_money_info = (TextView) findViewById(R.id.tv_money_info);
        tv_navigation = (MarqueeTextView) findViewById(R.id.tv_navigation);
        lv_moto_cade = (ListView) findViewById(R.id.lv_moto_cade);
        ptr_layout = (PtrClassicFrameLayout) findViewById(R.id.ptr_layout);
        rl_from = (RelativeLayout) findViewById(R.id.rl_from);
        rl_to = (RelativeLayout) findViewById(R.id.rl_to);
        rl_phone = (RelativeLayout) findViewById(R.id.rl_phone);
        tv_from = (TextView) findViewById(R.id.tv_from);
        tv_to = (TextView) findViewById(R.id.tv_to);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        ll_all = (LinearLayout) findViewById(R.id.ll_all);
        tv_sure = (TextView) findViewById(R.id.tv_sure);
        tv_sure.setOnClickListener(this);
        show(tv_sure);
        tv_sure.setText("添加订单");

        iv_back.setOnClickListener(this);
        rl_from.setOnClickListener(this);
        rl_to.setOnClickListener(this);
        rl_phone.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_sure:
                AddOrderActivity.open(this);
                break;
            case R.id.rl_from:
                KMSelectCityPW pw = new KMSelectCityPW(this, true);
                pw.showAtBottom(ll_all);
                pw.setOnResultListener(new KMSelectCityPW.OnResultListener() {
                    @Override
                    public void onResult(Address address) {
                        mAddressFrom = address;
                        tv_from.setText(address.city + address.region);
                        tv_money_tran.setText("运费总计：0元");
                        tv_money_info.setText("信息费总计：0元");
                        ptr_layout.setLoadMoreEnable(true);
                        page = 1;
                        tbItemOrders.clear();
                        getData();
                    }
                });
                break;
            case R.id.rl_to:
                KMSelectCityPW pwTo = new KMSelectCityPW(this, true);
                pwTo.showAtBottom(ll_all);
                pwTo.setOnResultListener(new KMSelectCityPW.OnResultListener() {
                    @Override
                    public void onResult(Address address) {
                        mAddressTo = address;
                        tv_to.setText(address.city + address.region);
                        tv_money_tran.setText("运费总计：0元");
                        tv_money_info.setText("信息费总计：0元");
                        ptr_layout.setLoadMoreEnable(true);
                        page = 1;
                        tbItemOrders.clear();
                        getData();
                    }
                });
                break;
            case R.id.rl_phone:
                final EditText etPhone = new EditText(this);
                new AlertDialog.Builder(this)
                        .setView(etPhone)
                        .setNegativeButton("清空", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                tv_phone.setText("");
                                tv_money_tran.setText("运费总计：0元");
                                tv_money_info.setText("信息费总计：0元");
                                ptr_layout.setLoadMoreEnable(true);
                                page = 1;
                                tbItemOrders.clear();
                                getData();
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                tv_phone.setText(etPhone.getText().toString());
                                tv_money_tran.setText("运费总计：0元");
                                tv_money_info.setText("信息费总计：0元");
                                ptr_layout.setLoadMoreEnable(true);
                                page = 1;
                                tbItemOrders.clear();
                                getData();
                            }
                        })
                        .setTitle("请输入电话号")
                        .create()
                        .show();
                break;
        }
    }

    /**
     * 网络请求
     */
    private void getData() {
        token = UserUtils.getToken();
        String url = Constants.HTTP_URL + HttpApi.MYORDERLIST;
        StringRequest request = new StringRequest(url, RequestMethod.POST);
        request.add("token", token);
        request.add("count", count);
        request.add("page", page);
        request.addNull("startAddress", mAddressFrom.city);
        request.addNull("destAddress", mAddressTo.city);
        request.addNull("phone", tv_phone.getText().toString());

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);

        CallServer.getInstance().request(Constants.ZERO, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                ptr_layout.refreshComplete();
                ptr_layout.loadMoreComplete(true);

                String result = response.get().getResult();
                Logger.e("请求成功：" + result);

                BaseTbItemOrder model = JSON.parseObject(result, BaseTbItemOrder.class);

                if (model != null) {
                    Integer status = model.getStatus();
                    String msg = model.getMsg();
                    //判断状态是
                    if (status != null && status == 0) {
                        TbItemOrderData data = model.getData();
                        if (data != null) {
                            hasMode = data.getHasMore();
                            //适配数据
                            List<TbItemOrder> tempList = data.getResultList();
                            if (tempList != null && tempList.size() > 0) {
                                tbItemOrders.addAll(tempList);
                                ptr_layout.setLoadMoreEnable(true);
                            } else {
                                ptr_layout.setLoadMoreEnable(false);
                            }

                            if (myOrderAdapter == null) {
                                myOrderAdapter = new MyOrderAdapter(MyOrderActivity.this);
                                myOrderAdapter.setTbItemOrders(tbItemOrders);
                                lv_moto_cade.setAdapter(myOrderAdapter);
                            } else {
                                myOrderAdapter.setTbItemOrders(tbItemOrders);
                                myOrderAdapter.notifyDataSetChanged();
                            }
                            if (!TextUtils.isEmpty(data.getArgs())) {
                                AmountBean ab = JSON.parseObject(data.getArgs(), AmountBean.class);
                                tv_money_tran.setText("运费总计：" + ab.getTransChargeSum() + "元");
                                tv_money_info.setText("信息费总计：" + ab.getItemChargeSum() + "元");
                            }

                        }

                    } else {
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                    }
                }


            }
        });
    }

    /**
     * 获取广告
     */
    private void getAD() {
        String url = Constants.HTTP_URL + HttpApi.ADVERTLIST;
        StringRequest request = new StringRequest(url, RequestMethod.POST);

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);

        CallServer.getInstance().request(Constants.ONE, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                closeDialog();

                String result = response.get().getResult();
                Logger.e("请求成功：" + result);

                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject != null) {
                    Integer status = jsonObject.getInteger("status");
                    String msg = jsonObject.getString("msg");

                    if (status != null && status == 0) {
                        List<String> data = JSON.parseArray(jsonObject.getJSONArray("data").toString(), String.class);
                        if (data != null && data.size() > 0) {
                            tv_navigation.init(data);
                        }

                    } else {
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();

                    }

                }

            }


        });
    }


    @Override
    public String getActiviyName() {
        return TAG;
    }

    @Subscriber(tag = Constants.UPDATEORDER)
    private void updateData(BaseModel baseModel) {
        ptr_layout.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptr_layout.autoRefresh(true);
            }
        }, 150);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
